package com.lzh.db.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lzh.db.handler.LzhMetaObjectHandler;
import com.lzh.db.properties.MybatisPlusAutoFillProperties;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zhehen.lu
 * @date 2025/8/22 11:01
 */
public class PrimaryMetaObjectHandler implements MetaObjectHandler, ApplicationContextAware, InitializingBean {
    @Autowired
    private MybatisPlusAutoFillProperties mybatisPlusAutoFillProperties;
    private ApplicationContext applicationContext;
    private List<LzhMetaObjectHandler> handlers = new ArrayList();

    public PrimaryMetaObjectHandler() {
        // TODO document why this constructor is empty
    }

    public void init() {
        Map<String, LzhMetaObjectHandler> handlerMap = this.applicationContext.getBeansOfType(LzhMetaObjectHandler.class);
        handlerMap.values().stream().filter((bean) -> {
            return !bean.equals(this);
        }).forEach((bean) -> {
            this.handlers.add(bean);
        });
    }

    @Override
    public boolean openInsertFill() {
        return this.mybatisPlusAutoFillProperties.getEnableInsertFill();
    }

    @Override
    public boolean openUpdateFill() {
        return this.mybatisPlusAutoFillProperties.getEnableUpdateFill();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.handlers.stream().filter((handler) -> !handler.equals(this)).forEach((handler) -> {
            handler.insertFill(metaObject);
        });
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.handlers.stream().filter((handler) -> !handler.equals(this)).forEach((handler) -> {
            handler.updateFill(metaObject);
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        this.init();
    }
}
